<template>
  <div class="goods-page">

    <!-- 操作按钮区域 -->
    <div class="card action-card">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus/>
        </el-icon>
        新增
      </el-button>
      <el-button type="danger" plain @click="delBatch">
        <el-icon>
          <Delete/>
        </el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 分类标签筛选 -->
    <div class="card filter-card">
      <!-- 全部标签 -->
      <el-tag
          :type="selectedCategoryId === null ? 'primary' : 'info'"
          style="margin-right: 8px; cursor: pointer"
          @click="handleCategoryClick(null)"
      >
        全部
      </el-tag>

      <!-- 分类标签 -->
      <el-tag
          v-for="category in data.categoryList"
          :key="category.id"
          :type="selectedCategoryId === category.id ? 'success' : 'info'"
          style="margin-right: 8px; cursor: pointer"
          @click="handleCategoryClick(category.id)"
      >
        {{ category.name }}
      </el-tag>
    </div>

    <!-- 表格区域 -->
    <div class="card table-card">
      <el-table
          stripe
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          class="main-table"
      >
        <el-table-column type="selection" align="center"/>
        <el-table-column prop="smallPicurl" label="壁纸" width="150" align="center">
          <template v-slot="scope">
            <el-image
                v-if="scope.row.smallPicurl"
                :src="scope.row.smallPicurl"
                fit="cover"
                style="width: 50px; height: 70px; border-radius: 5%;"
                :preview-src-list="[scope.row.smallPicurl]"
                preview-teleported
            />
            <div v-else class="no-avatar">无</div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="发布者" min-width="70"/>
        <el-table-column prop="score" label="评分" width="200" align="center">
          <template v-slot="scope">
            <el-rate v-model="scope.row.score" disabled show-score text-color="#ff9900"/>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="摘要" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="tabs" label="标签" width="160">
          <template v-slot="scope">
            <el-tag
                v-for="tag in scope.row.tabs"
                :key="tag"
                size="small"
                type="info"
                style="margin: 2px 4px"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="分类名称" width="80" align="center"/>
        <el-table-column prop="keywords" label="关键字" width="160" align="center"/>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template v-slot="scope">
            <el-button
                type="primary"
                size="small"
                :icon="Edit"
                circle
                @click="handleEdit(scope.row)"
                plain
            />
            <el-button
                type="danger"
                size="small"
                :icon="Delete"
                circle
                @click="del(scope.row.id)"
                plain
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域（可选，如果你需要分页） -->
    <!-- 注：当前用 selectAll，如数据多建议改为分页接口 -->
    <div class="card pagination-card" v-if="data.total">
      <el-pagination
          @current-change="load"
          background
          layout="prev, pager, next"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
          style="justify-content: center"
      />
    </div>

    <!-- 弹窗表单 -->
    <el-dialog
        title="每日推荐信息"
        v-model="data.formVisible"
        width="50%"
        max-width="600px"
        destroy-on-close
    >
      <el-form
          ref="form"
          :model="data.form"
          label-width="80px"
          :label-position="'right'"
          style="padding: 0 30px"
      >
        <el-form-item label="图片" prop="smallPicurl">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture-card"
              :limit="1"
              :file-list="[]"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">建议上传正方形头像图片</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="发布者" prop="nickname">
          <el-input v-model="data.form.nickname" placeholder="请输入发布者名称"/>
        </el-form-item>

        <el-form-item label="评分" prop="score">
          <el-rate v-model:value="data.form.score" show-score allow-half/>
        </el-form-item>

        <el-form-item label="摘要" prop="description">
          <el-input
              v-model="data.form.description"
              type="textarea"
              rows="4"
              placeholder="请输入内容摘要"
          />
        </el-form-item>

        <el-form-item label="标签" prop="tabs">
          <el-select
              v-model="data.form.tabs"
              multiple
              placeholder="请选择标签"
              style="width: 100%"
          >
            <el-option label="自然" value="自然"/>
            <el-option label="晨光" value="晨光"/>
            <el-option label="溪流" value="溪流"/>
            <el-option label="动物萌宠" value="动物萌宠"/>
            <el-option label="美食饮品" value="美食饮品"/>
            <el-option label="建筑" value="建筑"/>
            <el-option label="星空" value="星空"/>
            <el-option label="明星" value="明星"/>
            <el-option label="美女" value="美女"/>
          </el-select>
        </el-form-item>

        <el-form-item label="推荐">
          <el-switch v-model="data.form.recommend" active-text="推荐" inactive-text="不推荐"/>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="data.form.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in data.categoryList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="data.form.keywords" placeholder="请输入关键字"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL

// 响应式数据
const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  ids: [],
  categoryList: [],
  pageNum: 1,
  pageSize: 5,
  total: 0,
})

// 当前选中的分类 ID，null 表示全部
const selectedCategoryId = ref(null)

// 加载商品数据（支持按分类查询）
const load = () => {
  request.get('/goods/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      categoryId: selectedCategoryId.value  // 传递分类 ID
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || []
      data.total = res.data?.total
      data.tableData.forEach(item => {
        try {
          item.tabs = JSON.parse(item.tabs)
        } catch (e) {
          item.tabs = []
        }
      })
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    ElMessage.error('加载失败')
    console.error(err)
  })
}

// 点击分类标签
const handleCategoryClick = (categoryId) => {
  selectedCategoryId.value = categoryId
  load()  // 重新加载该分类数据
}

// 新增
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

// 添加
const add = () => {
  data.form.tabs = JSON.stringify(data.form.tabs)
  data.form.score = "0"
  request.post('/goods/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('添加成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 更新
const update = () => {
  data.form.tabs = JSON.stringify(data.form.tabs)
  request.put('/goods', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('更新成功')
      data.formVisible = false
      load()
    }
  })
}

// 保存
const save = () => {
  data.form.id ? update() : add()
}

// 删除单个
const del = (id) => {
  ElMessageBox.confirm('确定删除？', '警告', {type: 'warning'}).then(() => {
    request.delete('/goods/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据")
    return
  }
  ElMessageBox.confirm('确定删除选中的数据？', '警告', {type: 'warning'}).then(() => {
    request.delete("/goods/delete/batch", {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
        data.ids = []
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 选择变化
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

// 文件上传
const handleFileUpload = (res) => {
  data.form.smallPicurl = res.data
}

// 加载分类
const categoryData = () => {
  request.get('/category/selectAll').then(res => {
    data.categoryList = res.data || []
  })
}

// 初始化
import {ref} from 'vue'

categoryData()
load()  // 默认加载全部
</script>

<style scoped>
.goods-page {
  padding: 16px;
  background-color: #f9fafb;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 16px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-card {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-card {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding: 12px;
}

.table-card :deep(.el-table) {
  font-size: 14px;
}

.table-card :deep(.el-table th) {
  font-weight: 600;
  color: #333;
}

.no-avatar {
  width: 40px;
  height: 40px;
  background-color: #f0f0f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #999;
  margin: 0 auto;
}

.pagination-card {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.dialog-footer .el-button {
  padding-left: 20px;
  padding-right: 20px;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #c0ccda;
  border-radius: 8px;
}
</style>